package com.dtcnet.skmvp.mvp.presenter;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;

import com.dtcnet.skmvp.mvp.model.IModel;
import com.dtcnet.skmvp.mvp.view.IView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;

public class BasePresenter<V extends IView, M extends IModel> implements IPresenter {
    protected V mView;
    protected M mModel;

    protected LifecycleOwner owner;

    public BasePresenter() {
        initPresenter();
    }

    public BasePresenter(V mView) {
        this.mView = mView;

        initPresenter();
    }

    public BasePresenter(V mView, M mModel) {
        this.mView = mView;
        this.mModel = mModel;

        initPresenter();
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        IPresenter.super.onCreate(owner);
        this.owner = owner;

        if (mModel != null) {
            owner.getLifecycle().addObserver(mModel);
        }
    }

    /**
     * 初始化
     */
    protected void initPresenter() {

    }

    private List<Disposable> mDisposable;

    protected List<Disposable> getDisposable() {
        if (mDisposable == null) {
            mDisposable = new ArrayList<>();
        }
        return mDisposable;
    }

    protected void addDisposable(Disposable disposable) {
        if (mDisposable == null) {
            mDisposable = new ArrayList<>();
        }
        mDisposable.add(disposable);
    }

    protected void removeDisposable(Disposable disposable) {
        if (mDisposable != null) {
            if (!disposable.isDisposed()) disposable.dispose();
            mDisposable.remove(disposable);
        }
    }

    protected void cleanDisposable() {
        if (mDisposable != null) {
            for (Disposable arg : mDisposable) {
                if (arg != null && !arg.isDisposed()) {
                    arg.dispose();
                }
            }

            mDisposable.clear();
            mDisposable = null;
        }
    }


    @Override
    public void onDestroy(LifecycleOwner owner) {
        owner.getLifecycle().removeObserver(this);
        IPresenter.super.onDestroy();

        this.owner = null;

        mView = null;
        if (mModel != null)
            mModel.onDestroy();
        mModel = null;

        cleanDisposable();
    }
}
